<template>
  <div class="chart-item-container">
    <div v-if="loading"></div>
    <div ref="channelsChart" class="chart-item"></div>
  </div>
</template>

<script setup name="CaseSum">
import { ref, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue';
import useEcharts from '/@/utils/useEcharts';
import { usesStatisticsApi } from "/@/api/useAutoApi/statistics";

const loading = ref(true);
const channelsChart = ref(null);
let chartInstance = null;
let data = reactive([]);

const caseSum = async () => {
  const fetchData = await usesStatisticsApi().getSystemCaseSum();
  Object.assign(data, fetchData.data);
};

const init = () => {
  const option = {
    legend: {
      right: '10%',
      y: 'center',
      icon: 'circle',
      orient: 'vertical',
      formatter(name) {
        let total = 0;
        let target = 0;

        // 计算总值和目标值
        for (let i = 0; i < data.length; i++) {
          total += data[i].value || 0;
          if (data[i].name === name) {
            target = data[i].value || 0;
          }
        }

        const percentage = ((target / (total || 1)) * 100).toFixed(2);

        // 使用 padStart 和 padEnd 方法来确保固定宽度和对齐方式
        const nameFormatted = name.padEnd(4, ' ');
        const percentageFormatted = percentage.padEnd(6, ' ');
        const targetFormatted = target.toString().padStart(2, ' ');

        return [
          `{a|${nameFormatted}}`,
          `{b|${percentageFormatted}% }`,
          '{a| |  }',
          `{b|${targetFormatted}}`
        ].join('  ');
      },
      textStyle: {
        rich: {
          a: {
            fontSize: 12,
            color: 'var(--el-text-color-primary)',
          },
          b: {
            fontSize: 12,
            color: 'rgb(var(--el-color-primary))',
            fontWeight: 'bold',
          },
        },
      },
    },
    series: [
      {
        name: '访问来源',
        type: 'pie',
        center: ['30%', '50%'],
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 2,
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold',
          },
        },
        label: {
          show: false,
          position: 'center',
        },
        labelLine: {
          show: false,
        },
        data: data,
      },
    ],
  };

  nextTick(() => {
    if (channelsChart.value) {
      chartInstance = useEcharts(channelsChart.value);

      try {
        chartInstance.setOption(option);
        loading.value = false;
      } catch (error) {
        console.error('设置option失败:', error);
      }
    }
  });
};

const updateChart = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

onMounted(async () => {
  await caseSum();
  init();
});

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
});

defineExpose({
  loading,
  channelsChart,
  updateChart,
});
</script>

<style lang="scss" scoped>
.chart-item-container {
  .chart-item {
    height: 20vh;
  }
}
</style>
